package com.dz.lm.service.log.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.domain.log.LoginLog;
import com.dz.lm.domain.user.AccessToken;
import com.dz.lm.service.AbstractService;
import com.dz.lm.service.log.LoginLogService;

@Service
public class LoginLogServiceImpl extends AbstractService implements LoginLogService {
    private static final Logger logger = LoggerFactory.getLogger(LoginLogServiceImpl.class);
    
    @Resource
    private com.dz.lm.dao.log.read.LoginLogDao readLogindao;
    
    @Resource
    private com.dz.lm.dao.log.write.LoginLogDao writeLogindao;


    public LoginLogServiceImpl() {
        System.out.println(">>>>>>>>>>>>>>>>LoginLogServiceImpl()");
    }

    /**
     * 保存操作日志
     * @param param
     * @throws ServiceException
     */
    public void addLoginLog(Map<String, Object> param) throws ServiceException {
        try {
        	LoginLog log = new LoginLog();
        	log.setUserId((int) param.get("userId"));
        	Date day = new Date();
        	Timestamp ts = new Timestamp(day.getTime());
        	log.setLoginIp(param.get("ip")!= null?param.get("ip").toString():"");
        	log.setLoginTime(ts);
			log.setLoginPlatform(param.get("platform") != null ? param.get("platform").toString() : "");
			log.setAppVersion(param.get("appVersion") != null ? param.get("appVersion").toString() : "");
			log.setDeviceModel(param.get("deviceModel") != null ? param.get("deviceModel").toString() : "");
			log.setDeviceID(param.get("deviceId") != null ? param.get("deviceId").toString() : "");
			log.setOsVersion(param.get("osVersion") != null ? param.get("osVersion").toString() : "");
            writeLogindao.addLoginLog(log);
        } catch (DaoException e) {
            throw  new ServiceException(e,logger);
        }
    }
    
    /**
     * 保存token信息
     * @param param
     * @throws ServiceException
     */
    public void addAccessToken(Map<String, Object> param) throws ServiceException {
        try {
        	AccessToken token = new AccessToken();
        	token.setUserId((int) param.get("userId"));
        	token.setToken(param.get("token")!= null?param.get("token").toString() : "");
        	token.setPushId(param.get("jpushId")!= null?param.get("jpushId").toString() : "");
        	Date day = new Date();
        	Timestamp ts = new Timestamp(day.getTime());
        	token.setCreateTime(ts);
        	token.setUpdateTime(ts);
        	//先按userId更新token
        	int cnt = writeLogindao.updateAccessToken(token);
        	if (cnt <= 0) {
        		//无数据，新增一条
        		writeLogindao.addAccessToken(token);
        	}
            
        } catch (DaoException e) {
            throw  new ServiceException(e,logger);
        }
    }
}
